package tjx.Servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.*;

@WebServlet(name = "TestServlet",urlPatterns = {"/testServlet"},initParams = {
        @WebInitParam(name = "driver",value = "com.mysql.jdbc.Driver"),
        @WebInitParam(name = "url",value = "jdbc:mysql://localhost:3306/1613580002"),
        @WebInitParam(name = "username",value = "root"),
        @WebInitParam(name = "pass",value = "tjxwq42222"),
})
public class TestServlet extends HttpServlet {
  public void init(ServletConfig config) throws ServletException {
      super.init(config);
  }
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      try
      {
          ServletConfig config=getServletConfig();
          String driver=config.getInitParameter("driver");
          String url=config.getInitParameter("url");
          String username=config.getInitParameter("username");
          String pass=config.getInitParameter("pass");
          Class.forName(driver);
          Connection conn= DriverManager.getConnection(url,username,pass);
          Statement stmt=conn.createStatement();
          ResultSet rs=stmt.executeQuery("SELECT * FROM t_news");
          response.setContentType("text/html;charSet=UTF-8");
          PrintStream out=new PrintStream(response.getOutputStream());
          out.println("<html>");
          out.println("<head>");
          out.println("<title>访问Servlet初始化参数测试</title>");
          out.println("</head>");
          out.println("<body>");
          out.println("<table bgcolor=\"#9999dd\" border=\"1\""+"width=\"480\">");
          while(rs.next())
          {
              out.println("<tr>");
              out.println("<td>"+rs.getString(1)+"</td>");
              out.println("<td>"+rs.getString(2)+"</td>");
              out.println("</tr>");
          }
          out.println("</table>");
          out.println("<head>");
          out.println("</body>");
          out.println("</html>");
      } catch (ClassNotFoundException e) {
          e.printStackTrace();
      } catch (SQLException e) {
          e.printStackTrace();
      }
    }
}
